#include "renderthread.h"


QVector3D color(const ray&r,hitable*world,int depth)
{
    hit_record rec;
    if(world->hit(r,0.001,FLT_MAX,rec))
    {
        ray scattered;
        QVector3D attenuation;
        if(depth<10&&rec.mat_ptr->scatter(r,rec,attenuation,scattered))
        {
            return attenuation*color(scattered,world,depth+1);
        }
        else
        {
            return QVector3D(0,0,0);
        }

    }
    else
    {
        QVector3D unit_direction=r.direction().normalized();
        float t=0.5*(unit_direction.y()+1.0);
        return (1.0-t)*QVector3D(1.0,1.0,1.0)+t*QVector3D(0.5,0.7,1.0);
    }



}



void renderThread::render(renderThread*rt, scene*sc,QImage *image, int nx, int ny, int x1, int x2, int y1, int y2)
{
    if(rt!=this)
        return;
//    qDebug()<<QThread::currentThreadId()<<nx<<","<<ny<<","<<x1<<","<<x2<<","<<y1<<","<<y2<<"\n";
    int ns=25;


    for (int y =y1;y<y2;y++)
    {
        int yc=abs(image->height()-1-y);
        QRgb *line = (QRgb*)(image->scanLine(yc));
        for (int x = x1; x < x2; ++x)
        {
            QVector3D col(0,0,0);
            for(int s=0;s<ns;s++)
            {

                float u=float(x+Random::get(0.0,0.99))/nx;
                float v=float(y+Random::get(0.0,0.99))/ny;
                ray r=sc->cam->get_ray(u,v);
                col+=color(r,sc->world,0);
            }
            col/=float(ns);
            col=QVector3D(sqrt(col.x()),sqrt(col.y()),sqrt(col.z()));
            QRgb &rgb = line[x];
            rgb = qRgb(255*col[0],255*col[1],255*col[2]);
            emit refresh();
        }
    }
    emit renderfinished(QThread::currentThread());

}
